<template>
  <div class="associated-approval-container">
    <div class="top">
      <div v-if="isCustom && element" style="flex-shrink: 0;"><Title :element="element" is-table /></div>
      <div v-else style="flex-shrink: 0;"><SectionTitle :title="title" /></div>
      <div v-if="isRequired" class="is-required">*</div>
      <ToolTip v-if="tipText" :content="tipText" class="tip" />
      <div class="flex"/>
      <template v-if="isEdit">
        <PlainCreateBtn @click="todoListShow">添加</PlainCreateBtn>
        <el-button
          :disabled="!multipleSelectionAll.length"
          size="small"
          type="danger"
          plain
          class="option-btn"
          @click="handleMultipleDel">删除</el-button>
      </template>
    </div>
    <u-table
      ref="tableRef"
      :data="handleData"
      :row-height="49"
      :border="true"
      beautify-table
      header-drag-style
      class="fb-table todo-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell"
      fit
      hightlight-current-row
      row-class-name="pointer"
      @select="selectTable"
      @select-all="selectTable"
      @row-click="onRowClick">
      <EmptyPlaceholder slot="empty" mode="table" style="padding-bottom: 0"/>
      <u-table-column v-if="isEdit" :fixed="useFixed" align="center" type="selection" width="50" />
      <u-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          <div>{{ scope.$index + 1 }}</div>
        </template>
      </u-table-column>
      <template v-for="(settingItem, index) in tableFieldList">
        <u-table-column :key="index" v-bind="rowField[settingItem.field]">
          <template slot-scope="scope">
            <template v-if="settingItem.field === 'type'">
              <p :class="`task-type type${scope.row.type}`">{{ scope.row.type | getTaskType }}</p>
            </template>
            <template v-else-if="settingItem.field === 'proposerName'">
              <div class="column-creator">
                <img :src="scope.row.avatar || avatarPng" alt="发起人">
                <CheckUserInfo v-if="scope.row.proposerName" :label="scope.row.proposerName" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </div>
            </template>
            <template v-else-if="settingItem.field === 'publicDate'">
              <div>{{ formatTime(scope.row.createTime) }}</div>
            </template>
            <template v-else-if="settingItem.field === 'currentNode'">
              <ToolTip :content="scope.row.currentNode" />
            </template>
            <template v-else-if="settingItem.field === 'approvers'">
              <ToolTip :content="scope.row.approvers" />
            </template>
            <template v-else-if="settingItem.field === 'approverDate'">
              <div>{{ formatTime(scope.row.approveTime) }}</div>
            </template>
            <template v-else-if="settingItem.field === 'status'">
              <div class="color-status-box">
                <span v-if="scope.row.status !== null || scope.row.type === 12" :style="{backgroundColor: formatStatus(scope.row, 3).color}" class="dot"/>
                <p>{{ formatStatus(scope.row, 3).status }}</p>
              </div>
            </template>
            <template v-else-if="settingItem.field === 'abstract'">
              <template v-if="strJsonParse(scope.row.content) && scope.row.content !== '{}'">
                <div v-for="(val, name) in strJsonParse(scope.row.content)" :key="name">
                  <el-tooltip placement="top-start">
                    <div slot="content" style="max-width: 300px;">{{ `${name}：${val}` }}</div>
                    <div class="ellipsisOne" style="font-size: 12px">
                      <span style="color: #999">{{ name }}：</span>
                      <span>{{ (val || val === 0) ? val : '--' }}</span>
                    </div>
                  </el-tooltip>
                </div>
              </template>
              <div v-else>--</div>
            </template>
          </template>
        </u-table-column>
      </template>
      <u-table-column :width="operateWidth" :align="operateAlign" label="操作" fixed="right">
        <template slot-scope="scope">
          <template v-if="!showMobilePage">
            <el-button type="text" @click="toDetail(scope.row, false)">
              <span style="font-size:14px; color: #406eff">查看</span>
            </el-button>
            <el-button v-if="isEdit" type="text" @click="handleSingleDelete(scope.$index + (page-1)*perPage)">
              <span style="font-size:14px; color: red">删除</span>
            </el-button>
          </template>
          <tableOperateBtn v-else>
            <el-dropdown-item @click.native="toDetail(scope.row)">
              <div>查看</div>
            </el-dropdown-item>
            <el-dropdown-item @click.native="handleSingleDelete(scope.$index + (page-1)*perPage)">
              <div>删除</div>
            </el-dropdown-item>
          </tableOperateBtn>
        </template>
      </u-table-column>
    </u-table>
    <el-row :justify="showMobilePage ? 'start':'end'" type="flex" class="pagination-area">
      <el-pagination
        v-show="approvalList.length > 0"
        :current-page.sync="page"
        :page-size="perPage"
        :small="showMobilePage"
        :total="approvalList.length"
        :page-sizes="[10, 20, 50, 100, 250, 500]"
        :layout="showMobilePage?pageLayout:'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <TodoDialog
      ref="todoDialogRef"
      :table-field-list="dialogFieldList"
      :show-modal="showModal"
      :exclude-id="excludeId"
      :module-id="moduleId"
      :exclude-types="excludeTypes"
      @submit="handleSubmit" />
  </div>
</template>

<script>
// components
import SectionTitle from '@/components/Title';
import Title from '@/views/legal/process/components/formMake/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import TodoDialog from './todoDialog';
// img
import { showModal } from '@/utils/message';
import { tableField, rowField, customTableField } from '@/views/todo/fieldData';
import Todo from '@/mixins/todo';
import { strJsonParse } from '@/utils';
import { mapState } from 'vuex';
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';

export default {
  components: {
    SectionTitle,
    TodoDialog,
    EmptyPlaceholder,
    Title
  },
  mixins: [Todo, tableSelections, mobileTable],
  props: {
    title: {
      type: String,
      default: '关联审批'
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    excludeId: {
      type: String | Number,
      default: ''
    },
    moduleId: { // 所在模块
      type: Number,
      default: -1
    },
    excludeTypes: {
      type: String,
      default: ''
    },
    tipText: {
      type: String,
      default: ''
    },
    showModal: { // 是否显示遮罩
      type: Boolean,
      default: true
    },
    isRequired: {
      type: Boolean,
      default: false
    },
    isCustom: { // 是否自定义表单
      type: Boolean,
      default: false
    },
    element: { // 自定义表单的节点
      type: Object,
      default: null
    }
  },
  data() {
    return {
      rowField,
      newTabOpen: true,
      approvalList: [],
      page: 1,
      perPage: 10,
      tableRefName: 'tableRef',
      idKey: 'id',
      isUmyTable: true
    };
  },
  computed: {
    handleData() {
      return this.approvalList.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rangeKeyArr() {
      return [{
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }, {
        attr: 'approveTime',
        start: 'approveStart',
        end: 'approveEnd',
        type: 'time'
      }];
    },
    tableFieldList() {
      const field = this.isCustom ? _.cloneDeep(customTableField) : _.cloneDeep(tableField);
      if (field[0]['field'] !== 'type') {
        field.unshift({ name: '任务类型', field: 'type' });
      }
      return field;
    },
    dialogFieldList() {
      const field = _.cloneDeep(tableField);
      if (field[0]['field'] !== 'type') {
        field.unshift({ name: '任务类型', field: 'type' });
      }
      return field;
    }
  },
  methods: {
    strJsonParse,
    onRowClick(row, column) {
      if (column.label === '操作' || column.type === 'selection') return;
      this.toDetail(row, false);
    },
    todoListShow() {
      this.$refs['todoDialogRef'].openDrawer(this.approvalList);
    },
    handleSubmit(list) {
      this.approvalList = list;
      this.$emit('approvalListChange', list);
    },
    handleSingleDelete(index) {
      showModal('是否确定删除?').then(() => {
        this.approvalList.splice(index, 1);
        this.$emit('approvalListChange', this.approvalList);
      });
    },
    handleMultipleDel() {
      showModal('确认删除已选中的关联审批吗？').then(() => {
        while (this.multipleSelectionAll.length) {
          const curRow = this.multipleSelectionAll.pop();
          for (let index = this.approvalList.length - 1; index >= 0; index--) {
            if (this.approvalList[index].id === curRow.id) {
              this.approvalList.splice(index, 1);
            }
          }
        }
        this.$nextTick(() => {
          this.$emit('approvalListChange', this.approvalList);
        });
      });
    },
    getTableData() {
      if (this.approvalList.length) {
        return this.approvalList.map(item => item.id).join();
      } else {
        return '';
      }
    },
    setTableData(list) {
      this.approvalList = _.cloneDeep(list) || [];
    },
    // 本地分页
    handleSizeChange(val) {
      if (this.setSelectRow) {
        this.setSelectRow(this.approvalList);
      }
      this.perPage = val;
    },
    handleCurrentChange(val) {
      if (this.setSelectRow) {
        this.setSelectRow(this.approvalList);
      }
      this.page = val;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/views/todo/todoTable.scss";
.associated-approval-container {
  & ::v-deep {
    .cell {
      white-space: nowrap !important;
    }
    .el-table--border {
      border-bottom: 1px solid #eee !important;
    }
  }
  .option-btn {
    padding-left: 12px;
    padding-right: 12px;
  }
  .is-required {
    color: #F56C6C;
    margin-left: 3px;
  }
  .flex {
    flex:1;
  }
  .top {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }
}
</style>
